﻿using AspectInjector.Broker;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Prismx.Cool.Aop
{
    /// <summary>
    /// 日志打印 方法调用前以及方法调用后
    /// </summary>
    [Aspect(Scope.Global)]
    [Injection(typeof(LogAttribute))]
    [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Class)]
    public class LogAttribute : Attribute
    {
        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="name">方法名</param>
        /// <param name="arguments">参数</param>
        [Advice(Kind.Before)]
        public void LogBefore([Argument(Source.Metadata)] MethodBase name, [Argument(Source.Arguments)] object[] arguments)
        {
            if (!name.Name.Contains("ctor"))
            {
                try
                {
                    Log.Information($"'{name.DeclaringType.Name + "." + name.Name}'开始执行：，调用参数：{JsonConvert.SerializeObject(arguments)}");
                }
                catch
                {
                }
            }

        }

        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="name">方法名</param>
        /// <param name="arguments">参数</param>
        /// <param name="retrrnValue">返回值</param>
        [Advice(Kind.After)]
        public void LogAfter([Argument(Source.Metadata)] MethodBase name, [Argument(Source.Arguments)] object[] arguments, [Argument(Source.ReturnValue)] object retrrnValue)
        {
            if (!name.Name.Contains("ctor"))
            {
                try
                {
                    Log.Information($"'{name.DeclaringType.Name + "." + name.Name}'执行结束：，调用参数：{JsonConvert.SerializeObject(arguments)}，返回值为：{JsonConvert.SerializeObject(retrrnValue)}");
                }
                catch 
                {


                }
            }
        }
    }

}